<template>
  <div class="rooms-container">
    <el-table :data="rooms" border stripe>
      <el-table-column prop="room_name" label="会议室名称" width="180" />
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          {{ row.type === 'classroom' ? '教室型' : '圆桌型' }}
        </template>
      </el-table-column>
      <el-table-column prop="seats" label="座位数" width="100" />
      <el-table-column prop="status" label="状态" width="150">
        <template #default="{ row }">
          <el-select
            v-model="row.status"
            @change="handleStatusChange(row.room_id, row.status)"
          >
            <el-option label="空闲" value="idle" />
            <el-option label="锁定" value="locked" />
            <el-option label="已预订" value="booked" />
            <el-option label="使用中" value="using" />
            <el-option label="维护中" value="maintenance" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleViewOrders(row)">
            查看订单
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getRooms, updateRoomStatus } from '@/api/rooms'
import { ElMessage } from 'element-plus'

const router = useRouter()
const rooms = ref([])

const fetchRooms = async () => {
  try {
    const response = await getRooms()
    rooms.value = response
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  fetchRooms()
})

const handleStatusChange = async (roomId, status) => {
  try {
    await updateRoomStatus(roomId, status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error(error)
    fetchRooms() // 恢复原始状态
  }
}

const handleViewOrders = (room) => {
  router.push(`/employee/orders?room_id=${room.room_id}`)
}
</script>

<style scoped>
.rooms-container {
  padding: 20px;
}
</style>